The Copy Constructer
the first parameter is a reference to the class type.
usually not be eaplicit.
the difference between direct initialization and copy initialization.
direct initialization :the compiler use ordinary function matching to select the cnstructer that best matchs the arguments we provide;
copy initialization : the compiler copy the right oprand into the object being created,converting that operand if necessary.
12 string s(dots); // direct initializationstring s2 = dots; // copy initialization
Copy initialization happens
• Define variables using an =
• Pass an object as an argument to a parameter of nonreference type
• Return an object from a function that has a nonreference return type
• Brace initialize the elements in an array or the members of an aggregate class
• Some class types also use copy initialization for the objects they allocate.
insert or push:copy initialize empalce : direct initialized
The Copy-Assignment Operater
Assignment operators ordinarily should return a reference to their left-hand operand.copy-assignment
operator is function named operator=
.
and is used when assignment occurred.
The Destructor
prefixed by a tilde (~). no return value and takes no parameters:
When a Destructor Is Called
• Variables are destroyed when they go out of scope.
• Members of an object are destroyed when the object of which they are a part is
destroyed.
• Elements in a container—whether a library container or an array—are destroyed
when the container is destroyed.
• Dynamically allocated objects are destroyed when the delete operator is
applied to a pointer to the object
• Temporary objects are destroyed at the end of the full expression in which the
temporary was created.
|
|
Classes That Need Destructors Need Copy and Assignment
If a class needs a copy constructor, it almost surely needs a copy-assignment operator.
= default:use the defaluter constructer;(only on the default constructor or a copy-control member)
= delete: unable the constructer;
The Destructor Should Not be a Deleted Member
if a class has a data member that cannot be default
constructed, copied, assigned, or destroyed, then the corresponding member will be a
deleted function.
Copy Control and Resource Management
two points in assignment operator:
• Assignment operators must work correctly if an object is assigned to itself.
• Most assignment operators share work with the destructor and copy
constructor.
SteVec
Each StrVec will have three pointers into the space it uses for its elements:
• elements, which points to the first element in the allocated memory
• first_free, which points just after the last actual element
• cap, which points just past the end of the allocated memory